package com.wcq.studentbackend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcq.studentbackend.dto.ClassDTO;
import com.wcq.studentbackend.dto.ClassRequestDTO;
import com.wcq.studentbackend.entity.Class;
import com.wcq.studentbackend.mapper.ClassMapper;
import com.wcq.studentbackend.service.ClassService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 班级表 服务实现类
 * </p>
 *
 * @author Gemini
 * @since ${.now?date}
 */
@Service
public class ClassServiceImpl extends ServiceImpl<ClassMapper, Class> implements ClassService {

    // BaseMapper (this.baseMapper) 已经由 ServiceImpl 注入

    @Override
    public List<ClassDTO> getAllClasses() {
        List<Class> classList = list(); // list() 方法来自 IService
        return classList.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public ClassDTO getClassById(Integer id) {
        Class classEntity = getById(id); // getById() 方法来自 IService
        if (classEntity == null) {
            // 可以抛出自定义异常，例如 NotFoundException
            return null;
        }
        return convertToDTO(classEntity);
    }

    @Override
    @Transactional // 建议在写操作上加上事务注解
    public ClassDTO createClass(ClassRequestDTO classRequestDTO) {
        Class classEntity = new Class();
        BeanUtils.copyProperties(classRequestDTO, classEntity);
        // 手动设置创建和更新时间，或者配置MyBatis-Plus自动填充
        classEntity.setCreateTime(LocalDateTime.now());
        classEntity.setUpdateTime(LocalDateTime.now());
        
        save(classEntity); // save() 方法来自 IService
        return convertToDTO(classEntity);
    }

    @Override
    @Transactional
    public ClassDTO updateClass(Integer id, ClassRequestDTO classRequestDTO) {
        Class classEntity = getById(id);
        if (classEntity == null) {
            // 抛出异常或返回错误指示
            return null; 
        }
        BeanUtils.copyProperties(classRequestDTO, classEntity);
        classEntity.setUpdateTime(LocalDateTime.now());
        
        updateById(classEntity); // updateById() 方法来自 IService
        return convertToDTO(getById(id)); // 返回更新后的数据
    }

    @Override
    @Transactional
    public boolean deleteClass(Integer id) {
        // 在删除前可以添加业务校验，例如检查班级下是否还有学生
        return removeById(id); // removeById() 方法来自 IService
    }

    // Helper method to convert Entity to DTO
    private ClassDTO convertToDTO(Class classEntity) {
        if (classEntity == null) {
            return null;
        }
        ClassDTO classDTO = new ClassDTO();
        BeanUtils.copyProperties(classEntity, classDTO);
        return classDTO;
    }
} 